import type { FilterCriteria } from "../global.ts";
const useBuildSearchFilters = (props: any) => {
  const { searchFields } = props;
  // TODO: searchFields
  const buildKeywordSearchCondition = (searchKeyword) => {
    if (!searchKeyword) return {};
    const searchCondition: any = [];
    if (searchFields) {
      searchFields.forEach((field) => {
        searchCondition.push({ [field]: { $contains: searchKeyword } });
      });
      return {
        $or: searchCondition,
      };
    } else {
      return {};
    }
  };

  const buildSearchFilters = (searchData: any) => {
    let filters = {} as FilterCriteria;
    Object.entries(searchData ?? {}).forEach(([key, value]) => {
      if (key === "关键字" || key === "keyword") {
        filters = { ...filters, ...buildKeywordSearchCondition(value) };
        return;
      }
      if (props.searchFormFieldConfig) {
        const formItemConfig = props.searchFormFieldConfig.find(
          (item) => item.name === key
        );
        if (formItemConfig?.type === "dateRange") {
          if (value && Array.isArray(value) && value.length === 2) {
            filters[key] = {
              $gte: value[0].format("YYYY-MM-DD HH:mm:ss"),
              $lte: value[1].format("YYYY-MM-DD HH:mm:ss"),
            };
          }
        } else if (formItemConfig?.type === "timeRange") {
          if (value && Array.isArray(value) && value.length === 2) {
            filters[key] = {
              $gte: value[0].format("HH:mm:ss"),
              $lte: value[1].format("HH:mm:ss"),
            };
          }
        } else if (
          formItemConfig?.type === "select" &&
          Array.isArray(value) &&
          value.length === 1
        ) {
          filters[key] = { $eq: value[0] as any };
        } else if (value !== undefined && value !== null && value !== "") {
          filters[key] = { $eq: value as any };
        }
      }
    });
    return filters;
  };

  return { buildSearchFilters };
};

export default useBuildSearchFilters;
